package me.zhenqu.web.controller;

import me.zhenqu.model.pojo.entity.User;
import me.zhenqu.services.UserService;
import me.zhenqu.web.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller("publicController")
public class PublicController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index", method = GET)
    public String index() {
        return "redirect:/user/overview";
    }

    @RequestMapping(value = "/login", method = POST)
    public String signin(@RequestParam(value = "nick_name") final String nick_name,
                         @RequestParam(value = "password") final String password, final ModelMap modelMap, HttpSession session) {
        User cuuid = null;
        try {
            cuuid = userService.signIn(nick_name, password);
        } catch (Exception e) {
            modelMap.addAttribute("message", e.getMessage());
            return "signin";
        }
        if (cuuid == null){
            modelMap.addAttribute("message", "用户名密码不符");
            return "signin";
        }
        SessionUtil.setUser(session, cuuid);
        return "redirect:/user/overview";
    }

    @RequestMapping(value = "/signoff", method = GET)
    public String signoff(HttpSession session) {
        SessionUtil.removeUser(session);
        return "redirect:/signin";
    }

    @RequestMapping(value = "/signup", method = POST)
    public String signup(@RequestParam(value = "nick_name") final String nick_name,
                         @RequestParam(value = "password") final String password, @RequestParam(value = "repassword") final String repassword, HttpSession session) {
        signoff(session);
        User cuuid = null;
        if (!password.equals(repassword))
             return "redirect:/404";
        try {
            cuuid = userService.signup(nick_name,  password);
        } catch (Exception e) {
            return "redirect:/404";
        }
        if (cuuid == null)
            return "redirect:/404";
        SessionUtil.setUser(session, cuuid);
        return "redirect:/user/overview";
    }
}
